import React, {memo, useEffect, useState} from 'react'
import {
	ExclamationCircleFilled,
	QuestionCircleOutlined,
	PlusOutlined,
} from '@ant-design/icons'
import {Space, Button, Modal, message, Tooltip, Input} from 'antd'
import {connect, useHistory, useDispatch} from 'umi'
import type {ColumnsType} from 'antd/es/table'
import moment from 'moment'
import styles from './index.less'
import AdvancedSearchFrom from '@/components/SearchForm/advancedSearchFrom'
import {getDict} from '@/service/common/dict'
import {getList, cancelOrder, deleteOrder, editDDId} from '@/service/order'
import CustomTable from '@/components/Table'

import {businessType, planType} from '../dict'

import DDID from './columns/ddId'
import CahngeCar from './columns/changeCar'
import DelayRent from './columns/extendedLease'
import FreeRent from './columns/rentFree'
import ReturnCar from './columns/returnCar'
import TransferCar from './columns/transferCar'
import {downloadDocumentUrl} from '@/service/common/download'

const formItemLayout = {
	labelCol: {flex: '100px'},
	wrapperCol: {flex: '1'},
}

interface SearchOrderParam {
	current?: number // 当前页
	size?: number // 每页数量
	orderCarNo?: string // 订单编号
	orderCarStatus?: string // 订单状态
	lesseeName?: string // 司机名称
	rentType?: string // 订单类型 ???? 命名应该错误
	businessType?: string // 业务类型
	orderWay?: string // 下单方式
	planType?: string // 方案类型（字典：新签/续租）
	startTimeStarts?: string // 租赁开始日
	finishTimeStarts?: string // 租赁结束日
	deliveryTimeStarts?: string // 交车时间
}

const OrderList = memo(() => {
	const history = useHistory()
	const dispatch = useDispatch()
	// 搜索条件
	const [formValue, setFormValue] = useState({})
	const [importDriverId, setImportDriverId] = useState(false) // 导入滴滴非滴滴司机ID
	const [batchDelayRent, setBatchDelayRent] = useState(false) // 批量延租
	const [batchFreeRent, setBatchFreeRent] = useState(false) // 批量免租
	const [list, setList] = useState<any[]>([])
	const [loading, setLoading] = useState(false)
	const [importReturnCarItem, setImportReturnCarItem] = useState(false) // 导入退车费用项
	const [importTransferItem, setImportTransferItem] = useState(false) // 导入换车费用项
	const [importTransferCarItem, setImportTransferCarItem] = useState(false) // 导入过户费用项
	const [changeList, setChangeList] = useState([]) // 非滴滴ID改变的数组
	const [total, setTotal] = useState() // 分页
	const [searchValue, setSearchValue] = useState<any>() // 搜索条件
	const [params, setParams] = useState({
		size: 10,
		current: 1,
	})
	const [dict, setDict] = useState({
		order_car_status: [], // 订单状态
		order_rent_type: [], // 订单类型
		order_way: [], // 下单方式
	})
	const [formItem, setFormItem] = useState()
	// 搜索字段参数
	const formData: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '订单编号',
					name: 'orderCarNo',
					key: 'orderCarNo',
					placeholder: '请输入订单编号',
				},
				{
					type: 'select',
					key: 'orderCarStatus',
					name: 'orderCarStatus',
					placeholder: '请选择订单状态',
					label: '订单状态',
					keys: 'dictKey',
					title: 'dictValue',
					items: dict?.order_car_status,
				},
				{
					type: 'input',
					label: '司机名称',
					name: 'lesseeName',
					key: 'lesseeName',
					placeholder: '请输入司机名称',
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'select',
					key: 'rentType',
					name: 'rentType',
					placeholder: '请选择订单类型',
					label: '订单类型',
					keys: 'dictKey',
					title: 'dictValue',
					items: dict?.order_rent_type,
				},
				{
					type: 'select',
					key: 'businessType',
					name: 'businessType',
					label: '业务类型',
					placeholder: '请选择业务类型',
					keys: 'key',
					title: 'label',
					items: [...businessType],
				},
				{
					type: 'dateRange',
					label: '租赁开始日',
					placeholder: '租赁开始时间范围',
					name: 'startTimeStarts',
					key: 'startTimeStarts',
					// subtype: 'date',
				},
			],
		},
		{
			type: 'group',
			key: 'group3',
			groupItems: [
				{
					type: 'dateRange',
					label: '租赁结束日',
					placeholder: '租赁结束日时间范围',
					name: 'finishTimeStarts',
					key: 'finishTimeStarts',
					// subtype: 'date',
				},
				{
					type: 'dateRange',
					label: '交车时间',
					placeholder: '交车时间范围',
					name: 'deliveryTimeStarts',
					key: 'deliveryTimeStarts',
					// subtype: 'date',
				},
				{
					type: 'select',
					key: 'orderWay',
					name: 'orderWay',
					label: '下单方式',
					placeholder: '请选择下单方式',
					keys: 'dictKey',
					title: 'dictValue',
					items: dict?.order_way,
				},
			],
		},
		{
			type: 'group',
			key: 'group4',
			groupItems: [
				{
					type: 'select',
					key: 'planType',
					name: 'planType',
					label: '新签/续租',
					placeholder: '请选择新签/续租',
					keys: 'key',
					title: 'label',
					items: [...planType],
					span: 8,
				},
			],
		},
	]
	// 订单列表
	const getOrderList = () => {
		setList([])
		setLoading(true)
		const obj = {...params, ...searchValue}
		getList(obj)
			.then((res: any) => {
				if (res?.success) {
					setList(res?.data?.records)
					setTotal(res?.data?.total)
				}
				setLoading(false)
			})
			.catch((err) => {
				message.error(err)
			})
	}
	useEffect(() => {
		getOrderList()
	}, [params])

	useEffect(() => {
		getDict(
			{
				dictKeys: ['order_car_status', 'order_rent_type', 'order_way'],
			},
			(res: any) => {
				setDict(res)
			},
		)
	}, [])

	/**
	 *
	 * @param id 订单ID
	 * @param path  跳转路由地址
	 */
	const getDetails = (id: string, path: string) => {
		history.push(path)
		dispatch({
			type: 'order/updateOrderDetail',
			payload: {details: {id}},
		})
	}
	// 绑车
	const onOperateOrder = (id: number, path: string) => {
		dispatch({
			type: 'order/updateOrderDetail',
			payload: {details: {id}},
		})
		history.push(path)
	}
	// 查询
	const onFinish = (values: any) => {
		const data = {...values}
		// 租赁开始日
		if (data?.startTimeStarts) {
			data.startTimeStart = moment(data?.startTimeStarts[0]).format(
				'YYYY-MM-DD',
			)
			data.startTimeEnd = moment(data?.startTimeStarts[1]).format(
				'YYYY-MM-DD',
			)
		}
		// 租赁结束日
		if (data?.finishTimeStarts) {
			data.finishTimeStart = moment(data?.finishTimeStarts[0]).format(
				'YYYY-MM-DD',
			)
			data.finishTimeEnd = moment(data?.finishTimeStarts[1]).format(
				'YYYY-MM-DD',
			)
		}
		// 交车时间
		if (data?.deliveryTimeStarts) {
			data.deliveryTimeStart = moment(data?.deliveryTimeStarts[0]).format(
				'YYYY-MM-DD',
			)
			data.deliveryTimeEnd = moment(data?.deliveryTimeStarts[1]).format(
				'YYYY-MM-DD',
			)
		}
		delete data?.startTimeStarts
		delete data?.finishTimeStarts
		delete data?.deliveryTimeStarts
		setFormItem(data)
		setSearchValue(data)
		setParams({
			current: 1,
			size: 10,
		})
	}
	// 重置
	const onReset = () => {
		setSearchValue({})
		setParams({
			current: 1,
			size: 10,
		})
	}
	const btnList = [
		{
			text: '导出',
			type: 'primary',
			id: 'amc_order_export',
			onClick: () => {
				downloadDocumentUrl({
					resourceId: '181',
					queryDesc: '订单列表导出,resourceId:181',
					queryParam: formItem,
				})
			},
		},
		{
			text: '新增订单',
			icon: <PlusOutlined />,
			type: 'primary',
			ghost: 'ghost',
			id: 'amc_order_add',
			onClick: () => {
				history.push('/order/add')
			},
		},
		{
			text: '续租',
			type: 'button',
			id: 'amc_order_renewal',
			onClick: () => {
				history.push('/order/renewal')
			},
		},
		{
			text: '申请免租',
			type: 'button',
			id: 'amc_order_rentFree',
			onClick: () => {
				setBatchFreeRent(true)
			},
		},
		{
			text: '申请延租',
			type: 'button',
			id: 'amc_order_rentDelay',
			onClick: () => {
				setBatchDelayRent(true)
			},
		},
		{
			text: '申请费用减免',
			type: 'button',
			id: 'amc_order_derateFree',
			onClick: () => {
				history.push('/order/derateOrder')
			},
		},
		{
			text: '导入非滴滴司机ID',
			type: 'button',
			id: 'amc_order_importDriverId',
			onClick: () => {
				setImportDriverId(true)
			},
		},
		{
			text: '导入退车费用项',
			type: 'button',
			id: 'amc_order_importReturnCarItem',
			onClick: () => {
				setImportReturnCarItem(true)
			},
		},
		{
			text: '导入换车费用项',
			type: 'button',
			id: 'amc_order_importSwapCarItem',
			onClick: () => {
				setImportTransferItem(true)
			},
		},
		{
			text: '导入过户费用项',
			id: 'amc_order_importTransferOfOwnership',
			type: 'button',
			onClick: () => {
				setImportTransferCarItem(true)
			},
		},
	]
	const renderBtn = () => (
		<Space size={12} wrap>
			{btnList.map((item: any) => (
				// <Permissions permissionID={item.id}>
				<Button
					{...item}
					key={item.id}
					style={{
						color: '@primary-color',
						borderColor: '@primary-color',
						textShadow: 'none',
					}}>
					{item.text}
				</Button>
				// </Permissions>
			))}
		</Space>
	)
	/**
	 * 取消订单
	 * @param id 订单ID
	 */
	const onCancelOrder = (id: any) => {
		const config = {
			title: '提示',
			icon: <ExclamationCircleFilled />,
			content: '确认要取消此订单吗？取消后不可恢复。',
			onOk() {
				cancelOrder(id)
					.then((res: any) => {
						if (res?.success) {
							onReset()
							setFormValue({})
							message.success('取消成功')
						}
					})
					.catch(() => {})
			},
			onCancel() {},
		}
		Modal.confirm(config)
	}
	/**
	 * 删除订单
	 * @param id  订单ID
	 */
	const onDeleteOrder = (id: number) => {
		const config = {
			title: '提示',
			icon: <ExclamationCircleFilled />,
			content: '确认要删除此订单吗？',
			onOk() {
				setFormValue({})
				deleteOrder({ids: id}).then(() => {
					onReset()
				})
			},
			onCancel() {},
		}
		Modal.confirm(config)
	}
	// 操作列按钮
	const renderTagBtn = (record: any) => (
		<div style={{width: '100px'}}>
			<Button
				size="small"
				type="link"
				onClick={() => {
					dispatch({
						type: 'global/deleteTabs',
						payload: {
							menuname: ['订单中心', '订单列表'],
							asdefault: true,
							tabTitle: '订单详情',
							type: true,
							path: '/order/detail',
							component: '../pages/order/orderDetails/index.tsx',
						},
					})
					getDetails(record.id, `/order/details?id=${record.id}`)
				}}>
				查看
			</Button>
			{(record?.orderCarStatus === '11' ||
				record?.orderCarStatus === '12' ||
				record?.orderCarStatus === '13' ||
				record?.orderCarStatus === '14') &&
			record?.isRelet === 0 ? (
				<Button
					size="small"
					type="link"
					onClick={() => onCancelOrder(record.id)}>
					取消
				</Button>
			) : (
				<></>
			)}
			{record?.orderCarStatus === '1' ? (
				<Button
					size="small"
					type="link"
					onClick={() => onDeleteOrder(record.id)}>
					删除
				</Button>
			) : (
				<></>
			)}
			{record?.orderCarStatus === '12' ? (
				<Button
					size="small"
					type="link"
					onClick={() =>
						onOperateOrder(
							record.id,
							`/order/bindCar?type=carInfo/id=${record.id}`,
						)
					}>
					绑车
				</Button>
			) : (
				<></>
			)}
			{record?.orderCarStatus === '13' ? (
				<Button
					size="small"
					type="link"
					onClick={() =>
						onOperateOrder(
							record.id,
							`/order/checkCar?type=checkCarInfo/id=${record.id}`,
						)
					}>
					验车
				</Button>
			) : (
				<></>
			)}
			{record?.orderCarStatus === '16' ? (
				<Button
					size="small"
					type="link"
					onClick={() =>
						onOperateOrder(
							record.id,
							`/order/deliveryCar?type=deliveryCarInfo/id=${record.id}`,
						)
					}>
					交车
				</Button>
			) : (
				<></>
			)}
			{record?.orderCarStatus === '13' ? (
				<Button
					size="small"
					type="link"
					onClick={() =>
						onOperateOrder(
							record.id,
							`/order/bindCar?type=carInfos/id=${record.id}`,
						)
					}>
					重新绑车
				</Button>
			) : (
				<></>
			)}

			{record?.orderCarStatus === '14' ? (
				<Button
					size="small"
					type="link"
					onClick={() =>
						onOperateOrder(
							record.id,
							`/order/signing?type=contract/id=${record.id}`,
						)
					}>
					签约
				</Button>
			) : (
				<></>
			)}
			{record?.orderCarStatus === '20' ||
			record?.orderCarStatus === '21' ? (
				<Button
					size="small"
					type="link"
					onClick={() =>
						onOperateOrder(
							record.id,
							`/order/exchangeCar?type=exchangeCar/id=${record.id}`,
						)
					}>
					换车
				</Button>
			) : (
				<></>
			)}
			{record?.orderCarStatus === '40' &&
			record?.changeSettlementStatus === 0 ? (
				<Button
					size="small"
					type="link"
					onClick={() =>
						onOperateOrder(
							record.id,
							`/order/exchangeCar?type=exchangeCarInfo/id=${record.id}`,
						)
					}>
					换车费用项填写
				</Button>
			) : (
				<></>
			)}
			{record?.orderCarStatus === '20' ||
			record?.orderCarStatus === '21' ? (
				<Button
					size="small"
					type="link"
					onClick={() =>
						onOperateOrder(
							record.id,
							`/order/returnCar?type=returnCar/id=${record.id}`,
						)
					}>
					退车
				</Button>
			) : (
				<></>
			)}
			{record?.orderCarStatus === '30' &&
			record?.returnValidateStatus === 0 ? (
				<Button
					size="small"
					type="link"
					onClick={() =>
						onOperateOrder(
							record.id,
							`/order/returnCheckCar?type=returnCheckCar/id=${record.id}`,
						)
					}>
					退车验车
				</Button>
			) : (
				<></>
			)}
			{record?.orderCarStatus === '30' &&
			(record?.returnSettlementStatus === 0 ||
				record?.returnSettlementStatus === 2) &&
			record?.returnValidateStatus === 1 ? (
				<Button
					size="small"
					type="link"
					onClick={() =>
						onOperateOrder(
							record.id,
							`/order/returnCheckCar?type=returnCheckCars/id=${record.id}`,
						)
					}>
					退车费用项填写
				</Button>
			) : (
				<></>
			)}

			{(record?.orderCarStatus === '20' ||
				record?.orderCarStatus === '60' ||
				record?.orderCarStatus === '21') &&
			record?.transferSettlementStatus === 0 &&
			record?.rentType !== '1' ? (
				<Button
					size="small"
					type="link"
					onClick={() =>
						onOperateOrder(
							record.id,
							`/order/transferOfNames?type=transferOfNames/id=${record.id}`,
						)
					}>
					申请过户
				</Button>
			) : (
				<></>
			)}
			{record?.orderCarStatus === '61' &&
			(record?.transferSettlementStatus === 1 ||
				record?.transferSettlementStatus === 3) &&
			record?.rentType !== '1' ? (
				<Button
					size="small"
					type="link"
					onClick={() =>
						onOperateOrder(
							record.id,
							`/order/returnCheckCarInfo?type=returnCheckCarInfo/id=${record.id}`,
						)
					}>
					过户资料上传
				</Button>
			) : (
				<></>
			)}
		</div>
	)
	// 非滴滴司机输入框改变
	const inptChange = (e: any, value: any) => {
		list?.forEach((res: any) => {
			if (res?.id === value?.id) {
				res.platformDriverNo = e.target.value
			}
		})
		const lists: any = []
		const obj = {
			id: value?.id,
			value: e.target.value,
		}
		lists.push(obj)
		setChangeList(lists)
	}
	// 保存非滴滴司机ID
	const serveNoDDId = (value: any) => {
		changeList?.forEach((res: any) => {
			if (value?.id === res.id) {
				const regular = /^[A-Za-z0-9]+$/
				if (regular.test(res?.value)) {
					editDDId(res?.id, res?.value).then((res1: any) => {
						if (res1?.success) {
							message.success('修改成功')
						}
					})
				} else {
					message.error('请输入64位以内的数组或字母')
				}
			}
		})
	}
	const orderColumns: ColumnsType<TargetAPI.TargetColumns> = [
		{
			title: '订单编号',
			dataIndex: 'orderCarNo',
			align: 'center',
			key: 'orderCarNo',
			width: 300,
		},
		{
			title: '订单状态',
			dataIndex: 'orderCarStatusname',
			align: 'center',
			key: 'orderCarStatusname',
			width: 100,
		},
		{
			title: '下单方式',
			dataIndex: 'orderWayname',
			align: 'center',
			width: 100,
			key: 'orderWayname',
		},
		{
			title: '业务类型',
			dataIndex: 'businessTypename',
			align: 'center',
			width: 100,
			key: 'businessTypename',
		},
		{
			title: '订单类型',
			dataIndex: 'rentTypename',
			align: 'center',
			width: 100,
			key: 'rentTypename',
		},
		{
			title: '新签/续租',
			dataIndex: 'isRelet',
			align: 'center',
			width: 100,
			key: 'isRelet',
			render: (text: any) => <>{text === 0 ? <>新签</> : <>续签</>}</>,
		},
		{
			title: '车牌号',
			dataIndex: 'plateNo',
			align: 'center',
			width: 150,
			key: 'plateNo',
		},
		{
			title: '司机名称',
			dataIndex: 'driverName',
			align: 'center',
			width: 100,
			key: 'driverName',
		},
		{
			title: '所属公司',
			dataIndex: 'lessorName',
			align: 'center',
			width: 150,
			key: 'lessorName',
			ellipsis: true,
		},
		{
			title: '创建时间',
			dataIndex: 'createTime',
			align: 'center',
			width: 250,
			key: 'createTime',
		},
		{
			title: '租赁开始日',
			dataIndex: 'startTime',
			align: 'center',
			width: 250,
			key: 'startTime',
			render: (text: any) => <span>{text?.split(' ')[0]}</span>,
		},
		{
			title: '租赁结束日',
			dataIndex: 'finishTime',
			align: 'center',
			width: 250,
			key: 'finishTime',
			render: (text: any) => <span>{text?.split(' ')[0]}</span>,
		},
		{
			title: '租期',
			dataIndex: 'tenancy',
			align: 'center',
			width: 100,
			key: 'tenancy',
		},
		{
			title: '交车时间',
			dataIndex: 'deliveryTime',
			align: 'center',
			width: 250,
			key: 'deliveryTime',
		},
		{
			// eslint-disable-next-line react/no-unstable-nested-components
			title: () => (
				<span>
					<span style={{marginRight: '5px'}}> 非滴滴司机ID</span>
					<Tooltip
						placement="top"
						title="这里的非滴滴司机ID只适用于小平台，其他类型的为空">
						<QuestionCircleOutlined />
					</Tooltip>
				</span>
			),
			dataIndex: 'platformDriverNo',
			align: 'center',
			width: 250,
			key: 'platformDriverNo',
			render: (text, record) => (
				<div className="serveTb">
					<Input
						style={{width: '70%'}}
						onChange={(e) => inptChange(e, record)}
						value={text}
						maxLength={64}
					/>
					<Button
						style={{border: 'none', color: '#9A59FF'}}
						onClick={() => serveNoDDId(record)}>
						保存
					</Button>
				</div>
			),
		},
		{
			title: '操作',
			dataIndex: 'action',
			align: 'center',
			fixed: 'right',
			width: 120,
			render: (id, record) => renderTagBtn(record),
		},
	]

	// const rowSelection = {
	//   // onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
	//   // },
	// };
	const sunChange = (value: any) => {
		if (value) {
			setImportDriverId(false)
			setBatchDelayRent(false)
			setBatchFreeRent(false)
			setImportReturnCarItem(false)
			setImportTransferItem(false)
			setImportTransferCarItem(false)
		}
	}
	return (
		<div className={styles.page}>
			<div className={styles.search}>
				<AdvancedSearchFrom
					onFinish={onFinish}
					onReset={onReset}
					formItems={formData}
					formLayout={formItemLayout}
					rows={2}
					values={formValue}
				/>
			</div>
			<div className={styles.btnList}>{renderBtn()}</div>
			<div className={styles.orderList}>
				<CustomTable
					pagination
					total={total}
					params={params}
					loading={loading}
					// callback={(pagination: any) => {
					// 	setParams(pagination)
					// 	console.log(searchValue, 'searchValue-----')
					// 	getOrderList(pagination, searchValue)
					// 	const data = {
					// 		current: pagination?.current,
					// 	}
					// 	setCurrentPage(data)
					// }}
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					columns={orderColumns}
					dataSource={list}
				/>
			</div>
			{/* 导入非滴滴司机ID */}
			<DDID
				info={importDriverId}
				sunchange={sunChange}
				getOrderList={getOrderList}
			/>
			{/* 申请延租 */}
			<DelayRent
				info={batchDelayRent}
				sunchange={sunChange}
				getOrderList={getOrderList}
			/>
			{/* 申请免租 */}
			<FreeRent
				info={batchFreeRent}
				sunchange={sunChange}
				getOrderList={getOrderList}
			/>
			{/* 导入退车费用项 */}
			<ReturnCar
				info={importReturnCarItem}
				sunchange={sunChange}
				getOrderList={getOrderList}
			/>
			{/* 导入换车费用项 */}
			<CahngeCar
				info={importTransferItem}
				sunchange={sunChange}
				getOrderList={getOrderList}
			/>
			{/* 导入过户费用项 */}
			<TransferCar
				info={importTransferCarItem}
				sunchange={sunChange}
				getOrderList={getOrderList}
			/>
		</div>
	)
})

export default connect(({order}: any) => ({
	order,
}))(OrderList)
